import { React, toNode, useRef } from 'DoraX';
import {
  App,
  Audio,
  Body,
  BodyMoveType,
  Color,
  DrawNode,
  Ease,
  Label,
  Node,
  Scale,
  Sequence,
  Size,
  Sprite,
  Vec2,
  thread,
  wait,
} from 'Dora';

// ======================
// 音频与节奏配置
// ======================

const MUSIC_PATH = "audio/music.mp3";
const BEAT_INTERVAL_MS = 500; // 假设 BPM=120 → 每拍 500ms
const NOTE_SPAWN_OFFSET_MS = 300; // 提前 300ms 生成 Note

// ======================
// 全局状态（模拟类成员）
// ======================

let songStartTimeSystem: number | null = null;
const audioInstanceRef = { current: null as string | null }; // 存储 Audio ID
const isPlayingRef = { current: false };

// ======================
// 工具函数
// ======================

function getSongCurrentTimeMs(): number | null {
  if (audioInstanceRef.current) {
    try {
      const sec = Audio.getCurrentTime(audioInstanceRef.current);
      return sec * 1000;
    } catch (e) {
      print(`Error getting audio current time: ${e}`);
      return null;
    }
  }
  return null;
}

function msToBeat(ms: number): number {
  return ms / BEAT_INTERVAL_MS;
}

function beatToScreenY(beat: number, currentBeat: number): number {
  const beatsAhead = beat - currentBeat;
  return beatsAhead * 100; // 每拍垂直间距 100px
}

// ======================
// Tap 组件（带入场动画）
// ======================

interface TapProps {
  x: number;
  y: number;
  children?: any;
}

const Tap = (props: TapProps) => {
  return (
    <body
      type={BodyMoveType.Static}
      scaleX={0}
      scaleY={0}
      x={props.x}
      y={props.y}
      onMount={(self: Body.Type) => {
        // 正确创建带缓动的缩放动作
        const scaleAction = Scale(0.3, 1, 1);
        const easedAction = Ease.OutBack(scaleAction);
        self.runAction(easedAction);
      }}
    >
      <rect-fixture width={250} height={30} />
      <draw-node>
        <rect-shape
          width={250}
          height={30}
          fillColor={0x8800ffff}
          borderWidth={1}
          borderColor={0xff00ffff}
        />
      </draw-node>
      {props.children}
    </body>
  );
};

// ======================
// 主游戏逻辑
// ======================

export const GameScene = () => {
  const root = Node();
  const notesContainer = Node();
  notesContainer.position = Vec2(0, 0);
  notesContainer.addTo(root);

  // 启动主协程
  thread(function* () {
    // === 加载并播放音乐 ===
    if (!audioInstanceRef.current) {
      const musicId = Audio.load(MUSIC_PATH);
      if (musicId) {
        audioInstanceRef.current = musicId;
        Audio.play(musicId);
        songStartTimeSystem = App.totalTime;
        isPlayingRef.current = true;
        print("Music started");
      } else {
        print("Failed to load music");
        return;
      }
    }

    // === 节奏同步主循环 ===
    const noteBeats = [4, 8, 12, 16, 20, 24]; // 示例节拍点
    let nextNoteIndex = 0;

    while (isPlayingRef.current) {
      const songTimeMs = getSongCurrentTimeMs();
      if (songTimeMs === null) {
        yield; // 等待下一帧
        continue;
      }

      const currentBeat = msToBeat(songTimeMs);
      const spawnThresholdBeat = msToBeat(songTimeMs + NOTE_SPAWN_OFFSET_MS);

      // 生成新 Note
      while (
        nextNoteIndex < noteBeats.length &&
        noteBeats[nextNoteIndex] <= spawnThresholdBeat
      ) {
        const beat = noteBeats[nextNoteIndex];
        const screenY = beatToScreenY(beat, currentBeat);
        const noteNode = (
          <Tap x={0} y={screenY}>
            <label
              font="sarasa-mono-sc-regular"
              size={24}
              text={`Beat ${beat}`}
              color={Color(0xffffffff)}
              position={Vec2(0, 0)}
            />
          </Tap>
        );
        noteNode.addTo(notesContainer);
        nextNoteIndex++;
      }

      // 更新现有 Note 位置（简化版：实际应遍历子节点）
      // 此处省略动态更新逻辑，仅演示生成

      yield; // 下一帧
    }
  });

  return { node: root };
};
[x: string]: any;